import { Vector3 ,PerspectiveCamera} from '../libs/three137/three.module.js';
import { GLTFLoader } from '../libs/three137/GLTFLoader.js';
import { DRACOLoader } from '../libs/three137/DRACOLoader.js';
import { urls } from '../assets/store.js';

const {sin , cos, random,PI, max,  atan2} =Math
class Plane{
    constructor(game){
        this.loadingBar = game.loadingBar;
        this.game = game;
        this.scene = game.scene;
        this.camera = new PerspectiveCamera(45, window.innerWidth / window.innerHeight,.1, 100 )
        this.load();
        this.tmpPos = new Vector3();
        this.ready = false;
        this.velocity = new Vector3();
    }
    plane ;


    get position(){
        if (this.plane!==undefined) this.plane.getWorldPosition(this.tmpPos);
        return this.tmpPos;
    }

    set visible(mode){
        this.plane.visible = mode;
    }

    load(){
        const dracoLoader = new DRACOLoader() ;
        dracoLoader.setDecoderPath('../libs/three137/draco/') ;

    	const loader = new GLTFLoader( ) ;
        loader.setDRACOLoader(dracoLoader) ;
        this.ready = false;
        
		// Load a glTF resource
		loader.load(
			// resource URL
			urls.microplane,
			// called when the resource is loaded
			gltf => {
                console.log(gltf);
                this.scene.add(gltf.scene) ;
                this.plane = gltf.scene ;
                this.plane.add(this.camera) ;
                this.camera.position.copy(this.plane.position) ;
                this.camera.position.z+=6
                this.camera.lookAt(this.plane.position)
                //螺旋桨
                this.propeller = this.plane.children[0].children[6]
                // this.plane.rotateY(Math.PI)
                this.ready = true ;
			},
			// called while loading is progressing
			xhr => {
                this.loadingBar.update('plane', xhr.loaded, xhr.total)
			},
			// called when loading has errors
			err => {

				console.error( err );

			}
		);
	}	
    rock(t, Rz=true,Ry=true){ 
        if(this.plane){ 
           Rz && (this.plane.rotation.z = sin(t*4)*.3) ;
           Ry &&( this.plane.position.y = cos(t*2)*1.5) ;
           // z分量取反计算没问题， 问题是初始方向朝着z ,是 180,所以要加上它
           let angle = atan2(this.velocity.y,-this.velocity.z)+PI
           this.plane.rotation.x = angle ;
           // log的时候调用了normalize修改了它，真是
        //    console.log(...this.velocity, angle*180/PI);


        }
    }
    reset(){ 
        this.plane.position.set(0,0,0)
        this.velocity.set(0,0,0)
    }
    update(time){
        
        if (this.game.active){ 
            this.velocity.y+=(Number(this.game.spaceKey)-.5) * .005
            this.velocity.z+=.0005 ;//线速度在不断增加啊 加速度恒定。
            this.plane.position.add(this.velocity) ;
            // 螺旋桨
            if(this.propeller) {  this.propeller.rotation.z+=time /50; 
        }
            this.rock(time,1,0)
        }else { 

            
            this.rock(time)
        }
        
    }
}

export { Plane };